#!/usr/bin/env python
# -*- coding: utf-8 -*-

import sys
import time
import ldap
ldapuser = "CN=Tim,OU=System Accounts,OU=System Objects,DC=corp,DC=tudou,DC=com"
ldappass = "ZAQ!xsw2"
ldappath = "ldap://10.10.0.230:389/"
baseDN = "OU=tudou,DC=corp,DC=tudou,DC=com"

FoundResult_ServerBusy = "Server is busy"
FoundResult_NotFound = "Not Found"
FoundResult_Found = "Found"

def _validateLDAPUser(user):
    try:
        l = ldap.initialize(ldappath)
        l.protocol_version = ldap.VERSION3
        l.simple_bind(ldapuser,ldappass)
        print "bind to LDAP SERVER success"

        searchScope  = ldap.SCOPE_SUBTREE
        searchFiltername = "sAMAccountName"
        retrieveAttributes = None
        #searchFilter = 'c=cn'
        searchFilter = '(' + searchFiltername + "=" + user +')'

        ldap_result_id = l.search(baseDN, searchScope, searchFilter, retrieveAttributes)
        result_type, result_data = l.result(ldap_result_id,1)
        print result_data
        if(not len(result_data) == 0):
            return 1, FoundResult_Found
        else:
            return 0, FoundResult_NotFound
    except ldap.LDAPError, e:
        print e
        return 0, FoundResult_ServerBusy

def validateLDAPUser(user):
    i = 0
    isfound = 0
    foundResult = ""
    isfound, foundResult = _validateLDAPUser(user)

    print "-------------------------------"
    print "user is :" + user
    print "isfound :" + str(isfound)
    print "FoundResult : " + foundResult
    return isfound, foundResult


validateLDAPUser("tim")
